package cn.livenovel.thirddata.lottery;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import cn.livenovel.thirddata.dao.LotteryDAO;

/**
 * 彩票数据收集
 * 
 * @author shaohui
 * @date 2017-06-13 17:22:17
 */
@Service
public class LotteryDataCollect {

    @Autowired
    private RestTemplate restTemplate;
    
    private Logger logger = LoggerFactory.getLogger(LotteryDataCollect.class); 
    
    @Value("${jisuapi.appkey}")
    private String jisuAppkey;
    
    @Autowired
    private LotteryDAO lotteryDAO;
    
    /**
     * 
     * 批量爬双色球数据
     *
     * 
     * @author shaohui
     * @date 2017-06-14 16:49:13
     */
    public void batchCollectUnionLotto() {
//        collectUnionLotto
    }
    
    /**
     * 
     * 从文件导入
     *
     * @param dirPath
     * 
     * @author shaohui
     * @throws IOException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @date 2017-06-15 09:01:38
     */
    public void importFromFile(File dirPath) throws IOException, IllegalAccessException, InvocationTargetException {
        Collection<File> files = FileUtils.listFiles(dirPath, null, false);
        for (File file : files) {
            List<String> lines = FileUtils.readLines(file, "utf8");
            List<UnionLottoPO> pos = new ArrayList<>();
            for (String line : lines) {
                UnionLottoPO unionLottoPO = new UnionLottoPO();
                String[] items = line.split("\\s+");
                unionLottoPO.setIssue(Integer.parseInt(items[0]));
                String[] numbers = items[1].split("[,|]");
                for (int i = 0; i < 7; i++) {
                    int number = Integer.parseInt(numbers[i]);
                    if (i < 6) { // 红球
                        BeanUtils.setProperty(unionLottoPO, "red" + number, true);
                    } else { // 篮球
                        BeanUtils.setProperty(unionLottoPO, "blue" + number, true);
                    }
                }
                pos.add(unionLottoPO);
            }
            lotteryDAO.insertUnionLottos(pos);
        }
    }

    /**
     * 
     * 爬双色球数据
     *
     * 
     * @author shaohui
     * @date 2017-06-14 15:20:21
     */
    public UnionLottoPO collectUnionLotto(int issueno) {
        String response = restTemplate.getForObject("http://api.jisuapi.com/caipiao/query?appkey={appkey}&caipiaoid=13&issueno={issueno}", String.class, jisuAppkey); 
        logger.info("双色球接口响应：{}", response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("status") != 0) {
            logger.warn("非正常返回：{}", jsonObject.getString("msg"));
            return null;
        }
        UnionLottoPO po = new UnionLottoPO();
        JSONObject result = jsonObject.getJSONObject("result");
        String[] redNumbers = result.getString("number").split("\\s+");
        try {
            for (String redNumber : redNumbers) {
                BeanUtils.setProperty(po, "red" + Integer.parseInt(redNumber), true);
            }
            BeanUtils.setProperty(po, "blue" + Integer.parseInt(result.getString("refernumber")), true);
        } catch (Exception e) {
            logger.error("设值失败", e);
            return null;
        }
        po.setIssue(issueno);
        return po;
    }
    
}
